package org.budo.dubbo.protocol.http.authentication;

import java.io.Serializable;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
@Getter
@Setter
public class AuthenticationPrincipal implements Serializable {
    private static final long serialVersionUID = -4605741132439996375L;

    private Serializable type;

    private Serializable useId;

    public AuthenticationPrincipal(Serializable type, Serializable useId) {
        this.type = type;
        this.useId = useId;
    }

    public AuthenticationPrincipal(Serializable useId) {
        this.useId = useId;
    }

    public static Integer userIdInteger(AuthenticationCheckService authenticationCheckService) {
        if (null == authenticationCheckService) {
            log.error("#33 userId, authenticationCheckService=" + authenticationCheckService);
            return null;
        }

        Serializable principal = authenticationCheckService.getAuthenticationPrincipal();
        if (null == principal) {
            log.error("#39 userId, principal=" + principal + ", authenticationCheckService=" + authenticationCheckService);
            return null;
        }

        if (!(principal instanceof AuthenticationPrincipal)) {
            log.warn("#44 userId, principal=" + principal + ", principal.type=" + principal + ", authenticationCheckService=" + authenticationCheckService);
            return null;
        }

        Serializable userId = ((AuthenticationPrincipal) principal).getUseId();
        if (null == userId) {
            log.error("#50 userId=" + userId + ", principal=" + principal + ", authenticationCheckService=" + authenticationCheckService);
            return null;
        }

        if (!(userId instanceof Integer)) {
            log.error("#35 userId=" + userId + ", userId.type=" + userId + ", principal=" + principal + ", authenticationCheckService=" + authenticationCheckService);
            return null;
        }

        return (Integer) userId;
    }
}